<template>
    <el-dialog :close-on-click-modal="false" :visible.sync="show" width="800px" @close="close" append-to-body>
        <div slot="title" class="title"> 
            <span>选择联系人</span>
        </div>
        <div v-loading="loading" class="body">
            <div class="checkbox-list">
                <div class="filter">

                    <el-radio-group v-model="filterType" size="mini" v-if="type===0">
                        <el-radio-button :label="1">个人账号</el-radio-button>
                        <el-radio-button :label="2">公众号</el-radio-button>
                    </el-radio-group>  

                    <el-input
                        class="filter-input"
                        ref="filter-input"
                        size="mini"
                        :placeholder=" filterType===2?'请输入公众号名称':'请输入好友昵称或微信号' "
                        v-model="friendsFilterKeyword"
                        autofocus="true"
                        clearable>
                    </el-input>
                </div>
                
                <div class="scroller">
                    <el-row class="friend-list">
                        <div class="friend-list-inner">
                            <div class="friend-item-grid" v-for="(friend) in filteredFriends" :key="friend.id">
                                <label @click="checkfriend(friend)" :class="['friend-item',checkedIds.includes(friend.id)&&'is-success']">
                                    <friend 
                                        :avatar="friend.avatar"
                                        :name="friend.friendnick"
                                        :wxid="friend.friendalias||friend.friendwxid" 
                                        :gender="friend.friendsex"
                                    />
                                    <div class="friend-item-status-label">
                                        <i class="friend-item-check-success el-icon-check"></i>
                                    </div>
                                </label>
                            </div>    
                        </div>
                    </el-row>
                </div>
            </div>
            <el-divider class="divider" direction="vertical"></el-divider>
            <div class="checkbox-result">
                <div class="result-title">
                    已选择联系人（{{checkedfriends.length}}）
                </div>
                <div class="checked-list" ref="checked-list">
                    <div class="friend-list-inner" >
                        <div class="friend-col-item" v-for="(friend) in checkedfriends" :key="friend.id">
                            <el-avatar shape="square" :size="30" :src="friend.avatar"></el-avatar>
                            <div class="col-item-nick">{{friend.friendnick}}</div>
                            <!-- <div>{{friend.friendalias||friend.friendwxid}}</div> -->
                            <el-button @click="checkfriend(friend)" icon="el-icon-close" size="mini" circle></el-button>
                        </div>
                    </div>
                </div>
                
                <div class="button-group">
                    <el-button type="primary" @click="confirm" :disabled="!checkedIds.length">确定</el-button>
                    <el-button plain @click="cancel">取消</el-button>
                </div>
                
            </div>
            
        </div>
    </el-dialog> 
    
</template>
<script>
import friend from '@/components/friend'
import pinyin from '@/lib/pinyin'
/**
 * getSelectFriends
 * params = {}
 *  csid,wxaccout,
 *  multiple 多选单选
 *  type 只展示类别 0 全部 1 好友 2 公众号
 *  filterType 默认展示类别 1 好友 2 公众号
 */
export default {
    name:'dialog-select-friend',
    props:['visible'],
    components:{ friend },
    data(){
        return {
            show:false,
            loading:true,
            
            friendsFilterKeyword:'',
            checkedIds:[],
            friendsMap:{},
            friends:[],

            // UI 控制变量
            multiple:false, // 是否多选
            type:0,         // 展示类别
            filterType:1 ,  // 默认展示类别（type==0时生效）
            filterWxids:[]


        }    
    },
    
    computed:{
        filteredFriends() {
            const filterType = this.filterType
            const keyword = this.friendsFilterKeyword
            const keywordchars = pinyin.getFullChars(keyword).toLocaleLowerCase()
            return this.friends.filter(friend=>{
                const chars = pinyin.getFullChars(friend.friendalias+friend.friendwxid+friend.friendnick).toLocaleLowerCase()
                const isGH = friend.isbrand===1 || friend.isent ===1
                if(this.filterWxids.includes(friend.friendwxid))return false
                if( filterType===1 ){
                    return chars.indexOf(keywordchars)>-1 && !isGH
                }else{
                    return chars.indexOf(keywordchars)>-1 && isGH
                }

            })
        },
        checkedfriends(){
            return this.checkedIds.map(id=>this.friendsMap[id])
        }
         
    },
    methods:{
        checkfriend(friend){
            if(this.checkedIds.includes(friend.id)){ // 存在
                if(this.multiple){
                    const index = this.checkedIds.indexOf(friend.id)
                    this.checkedIds.splice(index,1)
                }else{
                    this.checkedIds = []     
                }
            }else{ // 不存在
                if(this.multiple){
                    this.checkedIds.push(friend.id)
                }else{
                    this.checkedIds = [friend.id] 
                }
                
            }
            this.scrollToEnd()
        },
        scrollToEnd(){
            const el_list = this.$refs['checked-list']
            const el_inner = el_list.firstChild
            this.$nextTick(()=>el_list.scrollTo(0,el_inner.offsetHeight))
        },
        requestFriends(params){
            this.loading = true
            this.$api.friend.list(params)
                .then(result=>{
                    this.loading = false
                    const data = this.formatData(result)
                    this.friends = data
                })
                .catch(e=>{
                    this.loading = false
                })
        },
        formatData(data){
            let map = {}
            data = data.map(item=>{
                map[item.id] = item
                item.certflag = (item.isbrand||item.isent)?24:0
                return item
            })
            this.friendsMap = map
            return data;
        },
        getSelectFriendsAsync( params = {csid: 2,wxaccount: "wxid_zlqc5vftkyr822"} ){
            return new Promise((resolve,reject)=>{
                this.getSelectFriends({...params,callback:(result) => {
                    resolve(result)    
                }})    
            })        
        },
        getSelectFriends( params ){
            this.callback = params.callback
            this.multiple = params.multiple
            this.filterWxids = params.filterWxids || []
            this.type = params.type || 0,         // 展示类别
            this.filterType = params.filterType || 1 

            if( params.type )this.filterType=this.type

            this.requestFriends(
                 { csid: params.csid,wxaccount: params.wxaccount } 
            )
            this.show = true 
        },
        reset(){
            this.result = undefined  
            this.checkedIds = []  
            this.friendsFilterKeyword=''
            this.friendsMap = {}
            this.friends = []
            this.filterWxids = []
        },
        confirm(){
            this.result = this.checkedfriends
            this.show = false
        },
        cancel(){
            this.show = false
        },
        close(){
            this.callback(this.result)
            this.reset()
        }
    }    
}
</script>

<style scoped>
.title{
    display: flex; flex-direction: row;justify-content: space-between;
}
.body{
    display: flex; flex-direction: row; height: 500px;
}

.filter{
    padding:0 10px 10px;
    display: flex;
    flex-direction: column;
    align-items: center;
}
.filter-input{
    margin-top: 10px;
}
.divider{
    display: block;
    height: 100%;
}
.checkbox-list{
    display: flex; flex-direction: column;
    width: 400px;
    flex-shrink: 0;  
}
.friend-list-inner{
    overflow: hidden;
}
.scroller{
    height: 100%;
    overflow: auto;
}

.friend-item-grid{
    width: 50%;
    float: left;
    padding: 5px;
    box-sizing: border-box;
}
.friend-item{
    display: block;
    position: relative;
    overflow: hidden;
    background-color: #fff;
    border: 1px solid #c0ccda;
    border-radius: 3px;
    box-sizing: border-box;
    padding: 10px 10px 10px 10px;
}

.friend-item-status-label {
    position: absolute;
    right: -17px;
    top: -7px;
    width: 46px;
    height: 26px;
    background: #13ce66;
    text-align: center;
    transform: rotate(45deg);
    box-shadow: 0 1px 1px #ccc;
    display: none
}
.friend-item-check-success{
    color: #fff;
    font-size: 12px;
    margin-top: 12px;
    transform: rotate(-45deg);
}
.is-success .friend-item-status-label{
    display: block
}


.checkbox-result{
    display: flex;
    flex-direction: column;
    flex:1;
}
.result-title{
    padding: 10px;
}
.checked-list{
    height: 100%;
    overflow:auto;
}

.friend-col-item{
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 5px 10px;
    border-radius: 5px;
}
.friend-col-item:hover{
    background: #f6f6f6
}
.col-item-nick{
    flex:1;
    padding-left: 10px;
}
.button-group{
    padding: 10px;
}
</style>